<template>
  <view class="todo-task" v-if="todoTask.visible">
    <view
      class="todo-task-countdown"
      v-if="isLogin && countdown > 0 && isInTaskPage"
      :style="{ top: isCustomTabBar ? `calc(${statusBarHeight}px + 88rpx)` : 0 }"
    >
      你正在完成{{ todoTask.taskName }}任务，还需要浏览<view class="countdown">{{ `${countdown}`.padStart(2, "0") }}秒</view>
    </view>

    <van-popup
      :show="visible"
      @close="cancel"
      custom-style="background: transparent; display: flex; flex-direction: column; justify-content: center; width: 100vw; height: 100vh"
    >
      <view class="todo-task-modal">
        <x-image src="https://staticcdn.youliao.com/static/image/www_pc/activity/signIn/todo-task.png" class="img" width="444rpx" height="298rpx" />
        <view class="finish-tip">恭喜你完成任务</view>
        <view class="finish-taskName">任务名称：{{ todoTask.taskName }}</view>

        <view class="fix-btn">
          <view class="btn" @click="cancel">知道了</view>
          <view class="return" @tap="toPage('/pages-activity/signIn/index')">返回打卡活动</view>
        </view>
      </view>
    </van-popup>
  </view>
</template>

<script>
import { mapMutations, mapGetters } from "vuex";
import marketService from "@/api/market";

export default {
  name: "todo-task",
  data() {
    return {
      isLogin: false,
      countdown: 0,
      isInTaskPage: false,
      visible: false,
      isCustomTabBar: false,
      statusBarHeight: 0
    };
  },
  mounted() {
    this.initCountdown();
  },
  methods: {
    ...mapMutations(["setTodoTask"]),
    initCountdown() {
      if (!this.todoTask.visible) return;
      const { screenHeight, windowHeight, statusBarHeight } = uni.getSystemInfoSync();
      this.isCustomTabBar = screenHeight === windowHeight;
      this.statusBarHeight = statusBarHeight;

      const token = uni.getStorageSync("yl_user_info");
      this.isLogin = !!token;

      setTimeout(this.taskRecordCreated, 1000);
    },

    taskRecordCreated() {
      if (!this.isLogin || !this.todoTask.id || !this.isInTaskPageHandle() || this.todoTask.isDone) return;
      this.setTodoTask({ ...this.todoTask, isDone: true });
      this.todoTask.countdown && (this.countdown = this.todoTask.countdown);
      this.clearInterval();

      this.setInterval = setInterval(async () => {
        if (this.todoTask.setInterval !== this.setInterval) {
          clearInterval(this.todoTask.setInterval);
        }
        console.log("countdown", this.countdown, this.todoTask);
        this.countdown--;
        if (this.countdown <= 0) {
          this.clearInterval();

          const { status, msg } = await marketService.finishSignCardTaskRecord({ id: this.todoTask.id });
          if (status !== 1) {
            uni.showToast({
              icon: "none",
              title: msg
            });
            this.cancel();
            return;
          }
          this.visible = true;
        }
      }, 1000);

      !this.todoTask.setInterval && this.setTodoTask({ ...this.todoTask, setInterval: this.setInterval });
    },

    cancel() {
      this.clearInterval();
      this.visible = false;
      this.countdown = 0;
      this.setTodoTask({ visible: false });
    },

    isInTaskPageHandle() {
      if (this.todoTask.isIndex === 1) {
        this.isInTaskPage = true;
        return true;
      }
      const routes = getCurrentPages();
      console.log(routes, "routes");
      const { route, options } = routes.pop();

      const query = Object.keys(options).reduce((total, curr) => {
        const joinStr = total ? "&" : "?";
        const value = options[curr];
        return value ? `${total}${joinStr}${curr}=${value}` : `${total}`;
      }, "");
      this.isInTaskPage = this.todoTask.path === `${route}${query}`;
      return this.isInTaskPage;
    },

    clearInterval() {
      clearInterval(this.setInterval);
      this.setInterval = null;
    },

    toPage(path) {
      const routes = getCurrentPages();
      console.log(routes, "routes");
      routes.length && this.todoTask.isIndex !== 1 ? uni.navigateBack() : uni.navigateTo({ url: path });
      this.cancel();
    }
  },
  computed: {
    ...mapGetters(["todoTask"])
  },
  beforeDestroy() {
    this.isInTaskPage && this.cancel();
  },
  watch: {
    // 主要解决pages/index 切换时组件不销毁的问题
    "todoTask.isIndex": function (isIndex) {
      if (isIndex === 1 && !this.todoTask.indexDone) {
        this.setTodoTask({ ...this.todoTask, indexDone: true });
        this.initCountdown();
      }
      isIndex === -1 && this.cancel();
      console.log(isIndex, "isIndex", this.todoTask.isDone);
    }
  }
};
</script>

<style lang="scss" scoped>
.todo-task {
  &-countdown {
    position: fixed;
    left: 0;
    width: 100vw;
    background-color: rgba(0, 0, 0, 0.6);
    z-index: 999;
    padding: 30rpx;
    box-sizing: border-box;
    color: #fff;
    text-align: center;

    .countdown {
      display: inline;
      color: #fd7801;
    }
  }

  &-modal {
    width: 690rpx;
    height: 685rpx;
    margin: auto;
    padding: 36rpx;
    box-sizing: border-box;
    background-image: linear-gradient(180deg, #fffde8 0%, #fffef5 100%);
    box-shadow: 0 6rpx 20rpx 0 rgba(0, 0, 0, 0.15);
    border-radius: 16rpx;
    text-align: center;
    position: relative;
    color: #6d1303;

    .img {
      margin: auto;
    }

    .finish-tip {
      font-size: 54rpx;
      margin-bottom: 20rpx;
      margin-top: -20rpx;
    }

    .finish-taskName {
      font-size: 36rpx;
    }

    .fix-btn {
      position: absolute;
      bottom: 46rpx;
      left: 76rpx;

      .btn {
        width: 534rpx;
        height: 91rpx;
        line-height: 91rpx;
        background-image: linear-gradient(180deg, #ffac70 0%, #ed572a 100%);
        border-radius: 45rpx;
        font-size: 32rpx;
        color: #fff;
      }

      .return {
        font-size: 24rpx;
        margin-top: 10rpx;
        color: #808080;
      }
    }
  }
}
</style>
